package com.tpp.threat_perception_platform.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class EncryptionUtils {

    // AES 解密方法
    public static String decrypt(String cipherText) throws Exception {
        // 固定密钥和 IV
        byte[] key = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
        byte[] iv = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);

        // 1. Base64 解码
        byte[] decodedBytes = Base64.getDecoder().decode(cipherText);

        // 2. 创建 AES 密钥
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

        // 3. 初始化 Cipher（AES/CBC/PKCS5Padding）
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, new javax.crypto.spec.IvParameterSpec(iv));

        // 4. 执行解密
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);

        // 5. 返回解密后的字符串
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static String encrypt(String plainText) throws Exception {
        // 固定密钥和 IV
        byte[] key = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);
        byte[] iv = "0123456789abcdef".getBytes(StandardCharsets.UTF_8);

        // 1. 创建 AES 密钥
        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

        // 2. 初始化 Cipher（AES/CBC/PKCS5Padding）
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, new javax.crypto.spec.IvParameterSpec(iv));

        // 3. 执行加密
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));

        // 4. Base64 编码
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);

        // 5. 返回加密后的字符串
        return encryptedText;
    }
}
